<?php
/**
 * Created by PhpStorm.
 * User: 张庭楷
 * Date: 2016/8/19
 * Time: 10:11
 */
namespace App\Http\Controllers\Business\App;

use App\Http\Controllers\Business\Shop\V1\CollectMoney\CollectMoney;
use App\Models\City;
use App\Models\Comment;
use App\Models\Order;
use App\Models\RedEnvelope;
use App\Models\Shop;
use App\Models\SmsMessage;
use App\Models\User;
use App\Models\HotWord;
use App\Models\ShopEvent;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PublicBusiness
{   //获取所有的城市
    public static function getCity() {
        $data = City::where('status','1')->select('id as cityid', 'name as cityname' , 'letter')->get();
        return ['status'=>'success','data'=>$data];
    }
    //商家列表
    public static function shopList($cityid,$event,$mylongitude,$mylatitude,$parameter=[],$sort='intelligent')
    {
        if(!$cityid) {
            return ['status'=>'failed','message'=>'未指定城市！'];
        }
        $select['cityid'] = $cityid;
        $select['status'] = 1;
        if(@$parameter['firstclassid']) {
            $select['firstclassid'] = $parameter['firstclassid'];
        }
        if(@$parameter['secondclassid']) {
            $select['secondclassid'] = $parameter['secondclassid'];
        }
        if(@$parameter['districtid']) {
            $select['districtid'] = $parameter['districtid'];
        }
        if(@$parameter['businessareaid']) {
            $select['businessareaid'] = $parameter['businessareaid'];
        }
        if(@$parameter['nextevent']) {
            $select['nextevent'] = $parameter['nextevent'];
        }
        $data = [];
        $order = '';
        $by = '';
        if($sort) {
            if($sort == 'intelligent') {
                $order = 'case when ordernumber<=10 then (distance * 0.6 + 1*0.4)  * case when commentmark=0 then 1 else commentmark / 10 end else (distance*0.6 + 30*0.4/ ordernumber) * case when commentmark=0 then 1 else commentmark / 10 end end';
                $by = 'asc';
            } elseif($sort == 'distance') {
                $order = 'distance';
                $by = 'asc';
            } elseif($sort == 'sales') {
                $order = 'ordernumber';
                $by = 'desc';
            } elseif($sort == 'commentmark') {
                $order = 'commentmark';
                $by = 'desc';
            } elseif($sort == 'newshop') {
                $order = 'ordernumber';
                $by = 'asc';
            } else {
                $order = 'distance';
                $by = 'asc';
            }
        } else {
            $order = 'distance';
            $by = 'asc';
        }
        if($mylongitude && $mylatitude) {
            $distance = 'round((round(6378137 * 2 * asin(sqrt(pow(sin(((latitude * pi()) / 180 - ('.$mylatitude.' * pi()) / 180) / 2), 2) + cos(('.$mylatitude.' * pi()) / 180) * cos((latitude * pi()) / 180) * pow(sin(((longitude * pi()) / 180 - ('.$mylongitude.' * pi()) / 180) / 2), 2)))))/1000,2) as distance';
            if($event == 'today') {
                $select['todayevent'] = 1;
                $data = Shop::where($select)->select('id as shopid','name','logo','secondclassname','label','districtname','businessareaname','todayevent','nextevent','commentmark','ordernumber')->selectRaw($distance)->orderBy(DB::raw($order),$by)->paginate(20);
            }
            if($event == 'next') {
                if(@$parameter['nextevent']) {
                    $shopdistance = 'round((round(6378137 * 2 * asin(sqrt(pow(sin(((91fbw_shops.latitude * pi()) / 180 - ('.$mylatitude.' * pi()) / 180) / 2), 2) + cos(('.$mylatitude.' * pi()) / 180) * cos((91fbw_shops.latitude * pi()) / 180) * pow(sin(((91fbw_shops.longitude * pi()) / 180 - ('.$mylongitude.' * pi()) / 180) / 2), 2)))))/1000,2) as distance';
                    $shopselect['shops.cityid'] = $cityid;
                    $shopselect['shops.status'] = 1;
                    $nextevent = $parameter['nextevent'];
                    if(@$parameter['firstclassid']) {
                        $shopselect['shops.firstclassid'] = $parameter['firstclassid'];
                    }
                    if(@$parameter['secondclassid']) {
                        $shopselect['shops.secondclassid'] = $parameter['secondclassid'];
                    }
                    if(@$parameter['districtid']) {
                        $shopselect['shops.districtid'] = $parameter['districtid'];
                    }
                    if(@$parameter['businessareaid']) {
                        $shopselect['shops.businessareaid'] = $parameter['businessareaid'];
                    }
                    $data = Shop::where($shopselect)->join("shop_events", 'shops.id', '=', 'shop_events.shopid')->where('shop_events.event', $nextevent)
                        ->select('shops.id as shopid', 'shops.name', 'shops.logo', 'shops.secondclassname', 'shops.label', 'shops.districtname', 'shops.businessareaname', 'shop_events.event as nextevent', 'shops.commentmark', 'shops.ordernumber')
                        ->selectRaw($shopdistance)
                        ->selectRaw('0 as todayevent')
                        ->orderBy(DB::raw($order),$by)
                        ->paginate(20);
                } else {
                    if ($order != '') {
                        $data = Shop::where($select)->where('nextevent', '>', date('Y-m-d', time()))
                            ->select('id as shopid', 'name', 'logo', 'secondclassname', 'label', 'districtname', 'businessareaname', 'nextevent', 'commentmark', 'ordernumber')
                            ->selectRaw($distance)
                            ->selectRaw('0 as todayevent')
                            ->orderBy('nextevent', 'asc')
                            ->orderBy(DB::raw($order),$by)
                            ->paginate(20);
                    } else {
                        $data = Shop::where($select)->where('nextevent', '>', date('Y-m-d', time()))
                            ->select('id as shopid', 'name', 'logo', 'secondclassname', 'label', 'districtname', 'businessareaname', 'nextevent', 'commentmark', 'ordernumber')
                            ->selectRaw($distance)
                            ->selectRaw('0 as todayevent')
                            ->orderBy('nextevent', 'asc')->paginate(20);
                    }
                }
                //$data = Shop::where($select)->where('todayevent', '0')->where('nextevent','>',date('Y-m-d',time()))->select('id as shopid','name','logo','secondclassname','label','districtname','businessareaname','todayevent','nextevent','commentmark','ordernumber')->selectRaw($distance)->orderBy($order,$by)->paginate(20);
            }
            if($event == 'occur') {
                $select['nightevent'] = 1;
                $select['forbidnightevent'] = 0;
                $data = Shop::where($select)->select('id as shopid','name','logo','secondclassname','label','districtname','businessareaname','todayevent','nextevent','commentmark','ordernumber')->selectRaw($distance)->orderBy(DB::raw($order),$by)->paginate(20);
            }
        } else {
            if($order == 'distance') {
                $order = 'ordernumber';
                $by = 'desc';
            } else {
                $order = "case when ordernumber<=10 then 1 * case when commentmark=0 then 1 else commentmark / 10 end else (1 / ordernumber) * case when commentmark=0 then 1 else commentmark / 10 end end";
                $by = 'asc';
            }
            if($event == 'today') {
                $select['todayevent'] = 1;
                $data = Shop::where($select)->select('id as shopid','name','logo','secondclassname','label','districtname','businessareaname','todayevent','nextevent','commentmark','ordernumber')
                    ->orderBy(DB::raw($order),$by)->paginate(20);
            }
            if($event == 'next') {
                if(@$parameter['nextevent']) {
                    $shopselect['shops.cityid'] = $cityid;
                    $shopselect['shops.status'] = 1;
//                    $shopselect['shops.todayevent'] = 0;
                    $nextevent = $parameter['nextevent'];
                    if(@$parameter['firstclassid']) {
                        $shopselect['shops.firstclassid'] = $parameter['firstclassid'];
                    }
                    if(@$parameter['secondclassid']) {
                        $shopselect['shops.secondclassid'] = $parameter['secondclassid'];
                    }
                    if(@$parameter['districtid']) {
                        $shopselect['shops.districtid'] = $parameter['districtid'];
                    }
                    if(@$parameter['businessareaid']) {
                        $shopselect['shops.businessareaid'] = $parameter['businessareaid'];
                    }
                    $data = Shop::where($shopselect)->join("shop_events", 'shops.id', '=', 'shop_events.shopid')->where('shop_events.event', $nextevent)
                        ->select('shops.id as shopid', 'shops.name', 'shops.logo', 'shops.secondclassname', 'shops.label', 'shops.districtname', 'shops.businessareaname', 'shop_events.event as nextevent', 'shops.commentmark', 'shops.ordernumber')
                        ->selectRaw('0 as todayevent')
                        ->orderBy(DB::raw($order), $by)->paginate(20);
                } else {
                    if ($order != '') {
                        $data = Shop::where($select)->where('nextevent', '>', date('Y-m-d', time()))
                            ->select('id as shopid', 'name', 'logo', 'secondclassname', 'label', 'districtname', 'businessareaname', 'nextevent', 'commentmark', 'ordernumber')
                            ->selectRaw('0 as todayevent')
                            ->orderBy(DB::raw($order), $by)->paginate(20);
                    } else {
                        $data = Shop::where($select)->where('nextevent', '>', date('Y-m-d', time()))
                            ->select('id as shopid', 'name', 'logo', 'secondclassname', 'label', 'districtname', 'businessareaname', 'nextevent', 'commentmark', 'ordernumber')
                            ->selectRaw('0 as todayevent')
                            ->orderBy('nextevent', 'asc')->paginate(20);
                    }
                }
            }
            if($event == 'occur') {
                $select['nightevent'] = 1;
                $select['forbidnightevent'] = 0;
                $data = Shop::where($select)->select('id as shopid','name','logo','secondclassname','label','districtname','businessareaname','todayevent','nextevent','commentmark','ordernumber')
                    ->orderBy(DB::raw($order),$by)->paginate(20);
            }
        }
        return ['status'=>'success','data'=>$data];
    }
    //获取距离
    public static function GetDistance($lat1, $lng1, $lat2, $lng2) {
        $earthRadius = 6378.137; // 地球半径值

        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;

        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return sprintf('%.2f',$calculatedDistance);
        //return sprintf('%.2f',$calculatedDistance/1000); //
    }
    //商家详情
    public static function shopDetails($shopid) {
        if(!$shopid) {
            return ['status'=>'failed','message'=>'缺少商家参数！'];
        }
        $data = Shop::where(array('id'=>$shopid))
            ->select('id as shopid','name','logo','maxsales','address','longitude','latitude','photos','description','label','districtname','businessareaname',
                'consumerinfo','invoice','notpartakegoods','content','contactnumber','buynumber','businesshours','commentnumber','commentmark',
                'ordernumber','nextevent','todayevent','nightevent','goodsphotos','firstclassid','cityid', 'firstclassname', 'secondclassname','status as shopstatus')
            ->first();
        if(!$data) {
            return ['status'=>'failed','message'=>'该商家已下架'];
        }
        $photos = json_decode($data['photos'], true);
        $goodsphotos = json_decode($data['goodsphotos'], true);
        $consumerinfo = json_decode($data['consumerinfo'], true);
        $data['photos'] = is_array($photos)? $photos : [];
        $data['goodsphotos'] = is_array($goodsphotos) ? $goodsphotos : [];
        $data['consumerinfo'] = is_array($consumerinfo) ? $consumerinfo : [];
        $data['tips'] = "为避免商品价格不实，翻贝网平台不显示商家价格，以用户和实体店最终议价为准，最后通过翻贝网代付。翻贝网热线：400-6989-820";
        $data['notpartakegoods'] = ($data['notpartakegoods'] == NULL) ? '': $data['notpartakegoods'];
        //除xxx外 全场参与 ，300元封顶，当天每个用户仅限1单
        if($data['notpartakegoods']) {
            $payinfo = "除" . $data['notpartakegoods'] . "外，全场参与，";
        } else {
            $payinfo = "全场参与，";
        }
        if($data['maxsales'] != '0') {
            $payinfo .= $data['maxsales'] . "元封顶，";
        }
        if($data['buynumber'] == '0') {
            $payinfo .= "";
        } else {
            $payinfo .= "当天每个用户仅限" . $data['buynumber'] . "单";
        }
        $data['payinfo'] = $payinfo;
        $data['content'] = ($data['content'] == NULL) ? '': $data['content'];
        $data['description'] = ($data['description'] == NULL) ? '': $data['description'];
        $mylongitude = $data['longitude'];
        $mylatitude = $data['latitude'];
        if ($mylongitude && $mylatitude) {
            $order = 'distance';
            $by = 'asc';
            $distance = 'round((round(6378137 * 2 * asin(sqrt(pow(sin(((latitude * pi()) / 180 - (' . $mylatitude . ' * pi()) / 180) / 2), 2) + cos((' . $mylatitude . ' * pi()) / 180) * cos((latitude * pi()) / 180) * pow(sin(((longitude * pi()) / 180 - (' . $mylongitude . ' * pi()) / 180) / 2), 2)))))/1000,2) as distance';
            $nearshop = Shop::where(array('todayevent' => '1', 'status' => '1', 'firstclassid' => $data['firstclassid'], 'cityid' => $data['cityid']))->where('id', '<>', $shopid)->select('id as shopid', 'name', 'logo')->selectRaw($distance)->orderBy($order, $by)->take(2)->get();
        } else {
            $nearshop = Shop::where(array('todayevent' => '1', 'status' => '1', 'firstclassid' => $data['firstclassid'], 'cityid' => $data['cityid']))->where('id', '<>', $shopid)->select('id as shopid', 'name', 'logo')->orderBy('ordernumber', 'desc')->take(2)->get();
        }

        if($nearshop) {
            $data['nearshop'] = $nearshop;
        }
        return ['status'=>'success','data'=>$data];
    }
    //通过商家id，获取商家简介
    public static function getBriefShopInfoByShopId($shopId) {
        if(!$shopId) {
            return ['status'=>'failed','message'=>'缺少商家参数！'];
        }
        $GLOBALS['shopid'] = $shopId;
        $data = Shop::where('status','1')
            ->where(function($query) {
                $query->orWhere('id', $GLOBALS['shopid'])
                    ->orWhere('qrcode', $GLOBALS['shopid']);
            })
            ->select('id as shopid','name','maxsales','address','notpartakegoods','buynumber','todayevent','nightevent')->first();
        if(!$data) {
            return ['status'=>'failed','message'=>'该商家已下架'];
        }
        $data['notpartakegoods'] = ($data['notpartakegoods'] == NULL) ? '': $data['notpartakegoods'];
        //除xxx外 全场参与 ，300元封顶，当天每个用户仅限1单
        if($data['notpartakegoods']) {
            $payinfo = "除" . $data['notpartakegoods'] . "外，全场参与，";
        } else {
            $payinfo = "全场参与，";
        }
        if($data['maxsales'] != '0') {
            $payinfo .= $data['maxsales'] . "元封顶，";
        }
        if($data['buynumber'] == '0') {
            $payinfo .= "当天每个用户不限买单次数";
        } else {
            $payinfo .= "当天每个用户仅限" . $data['buynumber'] . "单";
        }
        $data['payinfo'] = $payinfo;
        return ['status'=>'success', 'data'=>$data];
    }
    //翻贝日列表
    public static function doubleCalendarList($shopid)
    {
        $data = ShopEvent::where('shopid',$shopid)->select('event')->get();
        return ['status'=>'success','data'=>$data];
    }
    //获取两个月内的翻倍日
    public static function getTwoMonthDoubleCalendar($shopid) {
        $today = date('Y-m-d');
        $twoMonth = date('Y-m-d', strtotime("+2 month"));
        $data = ShopEvent::where('shopid', $shopid)->where('event', '>=', $today)
            ->where('event', '<=', $twoMonth)->orderBy('event', 'asc')->select('event')->get();
        return ['status'=>'success','data'=>$data];
    }
    //评论列表
    public static function commentList($shopid,$type = '') {
        if(!$shopid) {
            return ['status'=>'failed','message'=>'缺少商家参数！'];
        }
        if($type == '1') {
            $data = Comment::where('shopid',$shopid)->where('isdel', '0')->where('picture','!=','')->select('nickname','useravatar','score','content','picture','commenttime','replycontent','replytime')->orderBy('created_at', 'desc')->paginate(20);
        } else {
            $data = Comment::where('shopid',$shopid)->where('isdel', '0')->select('nickname','useravatar','score','content','picture','commenttime','replycontent','replytime')->orderBy('created_at', 'desc')->paginate(20);
        }
        return ['status'=>'success','data'=>$data];
    }
    //新增评论
    public static function newComment($ordernumber,$userid,$score,$content = '',$picture = '')
    {
        if(!$ordernumber || !$userid) {
            return ['status'=>'failed','message'=>'缺少参数！'];
        }
        $order = Order::where(array('ordernumber'=>$ordernumber,'userid'=>$userid,'commentstatus'=>'0'))->first();
        if($order) {
            $user = User::find($userid);
            $comment = new Comment;
            $comment->userid = $userid;
            $comment->nickname = $user['nickname'];
            $comment->useravatar = $user['avatar'];
            $comment->ordernumber = $ordernumber;
            $comment->score = $score;
            $comment->content = $content;
            if($picture) {
                $comment->picture = $picture;
            }
            $comment->commenttime = date('Y-m-d H:i:s',time());
            $comment->shopid = $order['shopid'];
            $comment->save();
            $order->commentstatus = '1';
            $order->commentscore = $score;
            $order->save();
            Shop::find($order['shopid'])->increment('commentscore', $score);
            Shop::find($order['shopid'])->increment('commentnumber', 1);
            $mark = Shop::find($order['shopid']);
            if($mark['commentnumber'] != '0') {
                $mark->commentmark = $mark['commentscore'] / $mark['commentnumber'];
                $mark->save();
            }
            Order::where('userid',$userid)->where('shopid',$order['shopid'])
                ->where('created_at','>',date('Y-m-d 00:00:00',time()))
                ->where('created_at','<',date('Y-m-d 23:59:59',time()))
                ->where('commentstatus','0')
                ->update(array('commentstatus'=>'2'));
            return ['status'=>'success','message'=>'评价提交成功！'];
        } else {
            return ['status'=>'failed','message'=>'提交失败！'];
        }
    }
    //搜索商家
    public static function searchShop($cityid,$string,$mylongitude = '',$mylatitude = '') {
        if(!$string || !$cityid) {
            return ['status'=>'failed','message'=>'缺少参数！'];
        }
        $searchstring = Redis::get('SearchString:'.$cityid.":".$string);
        if($searchstring) {
            Redis::incr('SearchString:'.$cityid.":".$string);
        } else {
            Redis::set('SearchString:'.$cityid.":".$string,'1');
        }
        $string = str_replace(array(" ","　","\t","\n","\r"),array("","","","",""),$string);
        $string = preg_split('/(?<!^)(?!$)/u', $string);
        $GLOBALS['search'] = '%';
        foreach ($string as $v) {
            $GLOBALS['search'] .= $v.'%';
        }
        if($mylongitude && $mylatitude) {
            $distance = 'round((round(6378137 * 2 * asin(sqrt(pow(sin(((latitude * pi()) / 180 - (' . $mylatitude . ' * pi()) / 180) / 2), 2) + cos((' . $mylatitude . ' * pi()) / 180) * cos((latitude * pi()) / 180) * pow(sin(((longitude * pi()) / 180 - (' . $mylongitude . ' * pi()) / 180) / 2), 2)))))/1000,2) as distance';
            $data = Shop::where(array('cityid'=>$cityid))
                ->where('name','not like','##作废%')
                ->where('status',1)
                ->where(function($query) {
                    $query->orWhere('firstclassname','like',$GLOBALS['search'])
                        ->orWhere('secondclassname','like',$GLOBALS['search'])
                        ->orWhere('businessareaname', 'like', $GLOBALS['search'])
                        ->orWhere('name','like',$GLOBALS['search'])
                        ->orWhere('label','like',$GLOBALS['search']);
                })
                ->select('id as shopid', 'name', 'logo', 'secondclassname', 'label', 'districtname', 'businessareaname', 'todayevent', 'nextevent', 'commentmark', 'ordernumber','status as shopstatus')->selectRaw($distance)->orderBy('status','desc')->orderBy('todayevent', 'desc')->orderBy('nextevent','desc')->orderBy('distance','asc')->paginate(20);
            return ['status'=>'success','data'=>$data];
        } else {
            $data = Shop::where(array('cityid'=>$cityid))
                ->where('name','not like','##作废%')
                ->where('status',1)
                ->where(function($query) {
                    $query->orWhere('firstclassname','like',$GLOBALS['search'])
                        ->orWhere('secondclassname','like',$GLOBALS['search'])
                        ->orWhere('businessareaname', 'like', $GLOBALS['search'])
                        ->orWhere('name','like',$GLOBALS['search'])
                        ->orWhere('label','like',$GLOBALS['search']);
                })
                ->select('id as shopid', 'name', 'logo', 'secondclassname', 'label', 'districtname', 'businessareaname', 'todayevent', 'nextevent', 'commentmark', 'ordernumber','status as shopstatus')->orderBy('status','desc')->orderBy('todayevent', 'desc')->orderBy('nextevent','desc')->paginate(20);
            return ['status'=>'success','data'=>$data];
        }
    }
    //获取搜索词
    public static function getSearchString() {
        $searcharray = Redis::keys('SearchString:*');
        $search = array();
        foreach ($searcharray as $k=>$v) {
            $search[$searcharray[$k]] = Redis::get($searcharray[$k]);
        }
        arsort($searcharray);
        return ['status'=>'success','data'=>$searcharray];
    }
    //热词
    public static function getHotWordList($cityId) {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = HotWord::where('cityid', $cityId)->select('name')->orderBy('sort', 'asc')->get();
        return ['status'=>'success', 'data'=>$data];
    }
    //加密函数encrypt($string,$operation,$key)中$string：需要加密解密的字符串；$operation：判断是加密还是解密，E表示加密，D表示解密；$key：密匙。
    public static function encrypt($string,$operation,$key=''){
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++){
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++){
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++){
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
                return substr($result,8);
            }else{
                return '';
            }
        }else{
            return str_replace('=','',base64_encode($result));
        }
    }

    //通过user-agent获取设备平台信息
    public static function getPlatformByUserAgent($userAgent) {
        if(strstr($userAgent, "FBWiOSApp")) {
            return "FBWiOSApp";
        } elseif(strstr($userAgent, "FBWAndroidApp")) {
            return "FBWAndroidApp";
        } elseif(strstr($userAgent, "Android")) {
            return "Android";
        } elseif(strstr($userAgent, "iphone")) {
            return "iOS";
        } elseif(strstr($userAgent, "ipad")) {
            return "iOS";
        } else {
            return '';
        }
    }
    //老的收款
    public static function collectMoney($userid,$shopid,$money) {
        if(!$shopid || !$money || !$userid) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $GLOBALS['shopid'] = $shopid;
        $user = User::find($userid);
        $shop = Shop::find($shopid);
        if($user && $shop) {
            //判断是不是超过买单次数限制
            $buynumber = $shop['buynumber'];
            $maxSales = $shop['maxsales'];
            if(($maxSales != 0)&&($maxSales != 0.00) && ($maxSales != '')) {
                if($maxSales < $money) {
                    return ['status'=>'failed', 'message'=>'已达封顶金额'.$maxSales];
                }
            }
            if($buynumber != 0) {
                $ordercount = Order::where('userid', $userid)->where('shopid', $shopid)->where('created_at', '>=', date('Y-m-d') . " 00:00:00")->get()->count();
                if ($ordercount >= $buynumber) {
                    $data = [
                        'ordernumber' => '',
                        'status' => '3' //付款失败，超过单日最大消费次数！
                    ];
                    return ['status' => 'success', 'data' => $data ];
                }
            }
            if($user['balance'] < $money) {
                $data = [
                    'ordernumber' => '',
                    'status' => '1' //用户余额不足！
                ];
                return ['status' => 'success', 'data' => $data ];
            }
            $mobile = substr($user['mobile'],7,10);
            $rand = '';
            for($i=0;$i<4;$i++) {
                $rand .= rand(0,9);
            }
            $ordernumber=date('ymdHis',time()).$rand.$mobile;
            $redenvelope = RedEnvelope::where(array('userid'=>$userid,'status'=>'0'))
                ->where('minimumamount','<=',$money)->where(function($query) {
                    $query->orWhere('shopid',$GLOBALS['shopid'])->orWhere('shopid','0');
                })->orderBy('amount','desc')->first();
            if($redenvelope) {
                $order = Order::where('userid',$userid)->first();
                if(!$order) {
                    $user->firstordertime = date('Y-m-d H:i:s',time());
                    $user->firstshopname = $shop['name'];
                    $user->save();
                }
                $redenvelope->status = '1';
                $redenvelope->save();
                $order = new Order();
                $order->startbalance = User::where('id',$userid)->pluck('balance')->first();
                User::find($userid)->decrement('balance', $money - $redenvelope['amount'] + env('COMMISSION_MONEY'));
                User::find($userid)->increment('savemoney', ($money - $redenvelope['amount'] + env('COMMISSION_MONEY'))/2);
                Shop::find($shopid)->increment('ordernumber', 1);
                $order->userid = $userid;
                $order->nickname = $user['nickname'];
                $order->shopid = $shopid;
                $order->shopname = $shop['name'];
                $order->shoplogo = $shop['logo'];
                $order->ordernumber = $ordernumber;
                $order->orderamount = $money;
                if($redenvelope['shopid']) {
                    $order->shopamount = $money - $redenvelope['amount'];
                    $order->fee = env('COMMISSION_MONEY');
                    $order->accountamount = round(($money - $redenvelope['amount'])/2,2);
                } else {
                    $order->shopamount = $money;
                    $order->fee = env('COMMISSION_MONEY') - $redenvelope['amount'];
                    $order->accountamount = round($money/2,2);
                }
                $order->actualamount = $money - $redenvelope['amount'] + env('COMMISSION_MONEY');
                $order->redenvelopeamount = $redenvelope['amount'];
                $order->redenvelopeid = $redenvelope['id'];
                $order->lastbalance = User::where('id',$userid)->pluck('balance')->first();
                $comment = Order::where('userid',$userid)->where('shopid',$shopid)
                    ->where('created_at','>',date('Y-m-d 00:00:00',time()))
                    ->where('created_at','<',date('Y-m-d 23:59:59',time()))
                    ->where('commentstatus','1')->first();
                if($comment)
                {
                    $order->commentstatus = '2';
                }
                $order->save();
            } else {
                $order = Order::where('userid',$userid)->first();
                if(!$order) {
                    $user->firstordertime = date('Y-m-d H:i:s',time());
                    $user->firstshopname = $shop['name'];
                    $user->save();
                }
                $order = new Order();
                $order->startbalance = User::where('id',$userid)->pluck('balance')->first();
                User::find($userid)->decrement('balance', $money + env('COMMISSION_MONEY'));
                User::find($userid)->increment('savemoney', ($money + env('COMMISSION_MONEY'))/2);
                Shop::find($shopid)->increment('ordernumber', 1);
                $order->userid = $userid;
                $order->nickname = $user['nickname'];
                $order->shopid = $shopid;
                $order->shopname = $shop['name'];
                $order->shoplogo = $shop['logo'];
                $order->ordernumber = $ordernumber;
                $order->orderamount = $money;
                $order->shopamount = $money;
                $order->fee = env('COMMISSION_MONEY');
                $order->actualamount = $money + env('COMMISSION_MONEY');
                $order->accountamount = round($money/2,2);
                $order->lastbalance = User::where('id',$userid)->pluck('balance')->first();
                $comment = Order::where('userid',$userid)->where('shopid',$shopid)
                    ->where('created_at','>',date('Y-m-d 00:00:00',time()))
                    ->where('created_at','<',date('Y-m-d 23:59:59',time()))
                    ->where('commentstatus','1')->first();
                if($comment)
                {
                    $order->commentstatus = '2';
                }
                $order->save();
            }
            CollectMoney::addShopSalesmanByOrder($userid, $ordernumber, $money, date('Y-m-d H:i:s'));
            $data = [
                'ordernumber' => $ordernumber,
                'status' => '2' //付款成功
            ];
            $smsMobileString = $shop['smsphone'];
            $smsMobileArray = explode(',', $smsMobileString);
            foreach($smsMobileArray as $smsMobile) {
                SmsMessage::collectMoneyToShop($smsMobile,$money);
            }
            return ['status'=>'success','data'=>$data];
        }
        else
        {
            return ['status'=>'failed', 'message'=>'系统错误！'];
        }
    }
    //新的收款
    //传人参数为，userid, shopid, money, method,
    //返回参数为 status: success, failed;
    //data: ['status'(1余额不足，2买单成功，3买单次数超过)， ordernumber,]
    public static function newCollectMoney($userId,$shopId,$money, $redEnvelopId, $redEnvelopMoney, $method) {
        if(!$shopId || !$money || !$userId || !$method) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $GLOBALS['shopid'] = $shopId;
        $user = User::find($userId);
        $shop = Shop::find($shopId);
        if($user && $shop) {
            //判断是不是超过买单次数限制
            $buyNumber = $shop['buynumber'];
            $maxSales = $shop['maxsales'];
            if(($maxSales != 0)&&($maxSales != 0.00) && ($maxSales != '')&&($maxSales<$money)) {
                return ['status'=>'failed', 'message'=>'已达封顶金额'.$maxSales];
            }
            if(self::isBuyNumberExceed($buyNumber, $userId, $shopId)) {
                //付款失败，超过单日最大消费次数！
                return ['status' => 'success', 'data' => ['ordernumber' => '', 'status' => '3' ]];
            }
            if($user['balance'] < $money) {
                //用户余额不足！
                return ['status' => 'success', 'data' => ['ordernumber' => '', 'status' => '1']];
            }
            $mobile = substr($user['mobile'],7,10);
            $rand = '';
            for($i=0;$i<4;$i++) {
                $rand .= rand(0,9);
            }
            $orderNumber=date('ymdHis',time()).$rand.$mobile;
            $order = Order::where('userid',$userId)->first();
            if(!$order) {
                //是否第一次买单
                $user->firstordertime = date('Y-m-d H:i:s',time());
                $user->firstshopname = $shop['name'];
                $user->save();
            }
            $redEnvelope = RedEnvelope::where(array('userid'=>$userId,'status'=>'0'))
                ->where('minimumamount','<=',$money)->where(function($query) {
                    $query->orWhere('shopid',$GLOBALS['shopid'])->orWhere('shopid','0');
                })->orderBy('amount','desc')->first();
            if($redEnvelope) {
                //有红包
                $redEnvelope->status = '1';
                $redEnvelope->save();
                $order = new Order();
                $order->startbalance = User::where('id',$userId)->pluck('balance')->first();
                User::find($userId)->decrement('balance', $money - $redEnvelope['amount'] );
                User::find($userId)->increment('savemoney', ($money - $redEnvelope['amount']));
                Shop::find($shopId)->increment('ordernumber', 1);
                $order->userid = $userId;
                $order->nickname = $user['nickname'];
                $order->shopid = $shopId;
                $order->shopname = $shop['name'];
                $order->shoplogo = $shop['logo'];
                $order->ordernumber = $orderNumber;
                $order->orderamount = $money;
                if($redEnvelope['shopid']) {
                    $order->shopamount = $money - $redEnvelope['amount'];
                    $order->fee = env('COMMISSION_MONEY');
                    $order->accountamount = round(($money - $redEnvelope['amount'])/2,2);
                } else {
                    $order->shopamount = $money;
                    $order->fee = env('COMMISSION_MONEY') - $redEnvelope['amount'];
                    $order->accountamount = round($money/2,2);
                }
                $order->actualamount = $money - $redEnvelope['amount'] + env('COMMISSION_MONEY');
                $order->redenvelopeamount = $redEnvelope['amount'];
                $order->redenvelopeid = $redEnvelope['id'];
                $order->lastbalance = User::where('id',$userId)->pluck('balance')->first();
                $comment = Order::where('userid',$userId)->where('shopid',$shopId)
                    ->where('created_at','>',date('Y-m-d 00:00:00',time()))
                    ->where('created_at','<',date('Y-m-d 23:59:59',time()))
                    ->where('commentstatus','1')->first();
                if($comment) {
                    $order->commentstatus = '2';
                }
                $order->save();
            } else {
                //无红包
                $order = new Order();
                $order->startbalance = User::where('id',$userId)->pluck('balance')->first();
                User::find($userId)->decrement('balance', $money + env('COMMISSION_MONEY'));
                User::find($userId)->increment('savemoney', ($money + env('COMMISSION_MONEY'))/2);
                Shop::find($shopId)->increment('ordernumber', 1);
                $order->userid = $userId;
                $order->nickname = $user['nickname'];
                $order->shopid = $shopId;
                $order->shopname = $shop['name'];
                $order->shoplogo = $shop['logo'];
                $order->ordernumber = $orderNumber;
                $order->orderamount = $money;
                $order->shopamount = $money;
                $order->fee = env('COMMISSION_MONEY');
                $order->actualamount = $money + env('COMMISSION_MONEY');
                $order->accountamount = round($money/2,2);
                $order->lastbalance = User::where('id',$userId)->pluck('balance')->first();
                $comment = Order::where('userid',$userId)->where('shopid',$shopId)
                    ->where('created_at','>',date('Y-m-d 00:00:00',time()))
                    ->where('created_at','<',date('Y-m-d 23:59:59',time()))
                    ->where('commentstatus','1')->first();
                if($comment) {
                    $order->commentstatus = '2';
                }
                $order->save();
            }
            //添加地推信息
            CollectMoney::addShopSalesmanByOrder($userId, $orderNumber, $money, date('Y-m-d H:i:s'));
            $smsMobileString = $shop['smsphone'];
            self::sendSmsToShopAfterOrder($smsMobileString, $money);
            //买单成功
            return ['status'=>'success','data'=> ['ordernumber' => $orderNumber, 'status' => '2']];
        } else {
            return ['status'=>'failed', 'message'=>'系统错误！'];
        }
    }
    //买单次数是否超过次数
    protected static function isBuyNumberExceed($buyNumber, $userId, $shopId) {
        if($buyNumber != 0) {
            $ordercount = Order::where('userid', $userId)->where('shopid', $shopId)->where('created_at', '>=', date('Y-m-d') . " 00:00:00")->get()->count();
            if ($ordercount >= $buyNumber) {
                return true;
            }
        }
        return false;
    }
    //买单以后给商家发送短信
    protected static function sendSmsToShopAfterOrder($smsMobileString, $money) {
        $smsMobileArray = explode(',', $smsMobileString);
        foreach($smsMobileArray as $smsMobile) {
            SmsMessage::collectMoneyToShop($smsMobile,$money);
        }
        return true;
    }

}